package com.example.cadmin.log;

import cn.hutool.core.date.DateUtil;
import com.example.cadmin.Application;
import com.example.cadmin.service.FileLogService;
import eu.bitwalker.useragentutils.UserAgent;
import com.example.cadmin.entity.FileLog;
import com.example.cadmin.security.dto.JwtUserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class FileLogInsert {
    /**操作数据库 */
//    @Autowired
//    public FileLogService fileLogService;
    /**
     * 自定义封装插入日志函数
     */
    public static void insert(String moduleName, String operation, Integer type,String number){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        FileLog fileLog = new FileLog();
        //获取用户信息
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(jwtUserDto != null) {
            Integer userId = jwtUserDto.getMyUser().getUserId();
            String userName = jwtUserDto.getMyUser().getUserName();
            fileLog.setUserId(userId);
            fileLog.setUserName(userName);
        }
        // 获取浏览器信息
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        fileLog.setBrowser(userAgent.getBrowser().getName());
        // 客户端ip
        fileLog.setLoginIp(request.getRemoteAddr());
        //操作类型
        fileLog.setType(type);
        // url
        String requestUrl = request.getRequestURI();
        fileLog.setUrl(requestUrl);
        //操作模块
        fileLog.setModuleName(moduleName);
        //操作内容
        fileLog.setOperation(operation);
        //创建时间
        fileLog.setCreateTime(DateUtil.now());
        //备注
        //机柜编号
        fileLog.setNumber(number);
        //数据逻辑删除
        fileLog.setStatus(1);
//        // 静态方法注入bean解决方案
        FileLogService adminlogService = Application.ac.getBean(FileLogService.class);
        adminlogService.save(fileLog);

    }
}
